package com.alex.utils.http;

import java.io.IOException;
import java.io.InputStream;
import java.util.zip.GZIPInputStream;

import org.apache.commons.io.IOUtils;
import org.apache.http.Header;
import org.apache.http.HeaderElement;
import org.apache.http.HttpHost;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.protocol.ExecutionContext;
import org.apache.http.protocol.HttpContext;
import org.apache.http.util.EntityUtils;

public abstract class HttpUtils {

	private static final byte[] EMPTY = new byte[0];

	public static String toString(HttpResponse response) throws IOException {
		if (response.getEntity() == null) {
			return "";
		}
		
		InputStream in = null;
		try {
			Header header = response.getFirstHeader("Content-Encoding"); 
			boolean gzip = header != null && header.getValue().contains("gzip");
			in = response.getEntity().getContent();
			if (gzip) {
				in = new GZIPInputStream(in);
			}
			return IOUtils.toString(in, EntityUtils.getContentCharSet(response.getEntity()));
		} finally {
			IOUtils.closeQuietly(in);
		}
	}
	
	public static String getResponseCharset(HttpResponse response) {
		String charset = null;
		Header contentType = response.getFirstHeader("Content-Type");
		if (contentType != null) {
			HeaderElement values[] = contentType.getElements();
            if (values.length > 0) {
                NameValuePair param = values[0].getParameterByName("charset");
                if (param != null) {
                    charset = param.getValue();
                }
            }
		}
		return charset;
	}
	
	public static byte[] toByteArray(HttpResponse response) throws IOException {
		if (response.getEntity() == null) {
			return EMPTY;
		}
		
		InputStream in = null;
		try {
			Header header = response.getFirstHeader("Content-Encoding"); 
			boolean gzip = header != null && header.getValue().contains("gzip");
			in = response.getEntity().getContent();
			if (gzip) {
				in = new GZIPInputStream(in);
			}
			return IOUtils.toByteArray(in);
		} finally {
			IOUtils.closeQuietly(in);
		}
	}
	
	public static String getFinalURL(HttpResponse response, HttpContext context) {
		HttpUriRequest request = (HttpUriRequest) context.getAttribute(ExecutionContext.HTTP_REQUEST);
		HttpHost finalHost = (HttpHost) context.getAttribute(ExecutionContext.HTTP_TARGET_HOST);
		return finalHost.toURI() + request.getURI();
	}
}